#include <LPC214x.H>                       /* LPC214x definitions */

typedef unsigned char uc;

#define RDR		0x01
#define THRE	0x20
#define RDA		0x04

#define UART0_CH_NUM	6 
#define VIC_UART0_CH	(0x01 << UART0_CH_NUM)
#define VIC_INT_CH_EN	(0x01 << 5)

#define MAX_BUFF_SZ	10

uc RX_BUFF[MAX_BUFF_SZ];
uc byteCount=0;


void UART0_ISR(void) __irq
{
 	if( U0IIR & RDA) 					/* Check if Recive data Interrupt event */
	{ 
		if(byteCount < MAX_BUFF_SZ)	   /* Validation for buffer overflow */
		{
	  		RX_BUFF[byteCount++] = U0RBR;
		}
	}
	VICVectAddr = 0x00;				  /* ACK the VIC */
}


void uart0_init()
{
   /* initialize the serial interface   */
  PINSEL0 = 0x00000005;           /* Enable RxD0 and TxD0                     */
  U0LCR = 0x83;                   /* 8 bits, no Parity, 1 Stop bit            */
  U0DLL = 97;                     /* 9600 Baud Rate @ 15MHz VPB Clock  
  									 U0DLL = 194 for 30MHz and 
  									U0DLM=  0x01; U0DLL = 0x84;  at VBP + 60MHz     */
  U0LCR = 0x03;                   /* DLAB = 0    */

	/* Enable Uart FIFO */
  U0FCR |= 0x01;
	/* Configure the VIC for Interrupt Handling */
	VICVectCntl8 |= (VIC_INT_CH_EN | UART0_CH_NUM);
	VICVectAddr8 = (unsigned int) UART0_ISR;
	VICIntSelect &= (~VIC_UART0_CH);	/* This is optional to ensure the IRQ Mode */
	VICIntEnable |= VIC_UART0_CH; 	  	/* Enabel the Interrupt for listening request */
   /* Enable UART Interrupt */
  U0IER	|= 0x01;
}


void put_char(uc dt)
{
 	while(!(U0LSR & THRE)); // Wait until UART0 ready to send character  
	U0THR = dt; // Send character

}

void puts(uc *st)
{
	while(*st) 
	{
		put_char(*st++);
	}
}

int main (void) 
{
	uart0_init();
	puts("UART0 Rx Interrupt Test");
  	while (1)
	{
		if(byteCount > 5)
		{
		  U0IER	= 0x00;		
		  RX_BUFF[byteCount] = '\0';
		  puts(RX_BUFF);
		  byteCount = 0;
		  U0IER	= 0x01;		
		}	
	}
}
